/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.dwusoft.wbd.send.impl  
 */
package com.dwusoft.sendmsg.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import com.apache.api.vo.ParamsVo;
import com.apache.cache.util.Validator;
import com.apache.database.constant.SpringContextLoader;
import com.apache.tools.DateUtils;
import com.apache.tools.MD5Utils;
import com.dwusoft.sendmsg.common.entity.Sendmsg;
import com.dwusoft.sendmsg.common.entity.TSmsService;
import com.dwusoft.sendmsg.manager.SendService;
import com.dwusoft.sendmsg.manager.SendmsgManager;
import com.dwusoft.sendmsg.manager.TSmsServiceManager;

/**
 * description:  向手机发短信通知
 * @author Hou Dayu 创建时间：2016-5-6  
 * @Copyright(c)2014:北京东吴软件技术有限公司
 */
public class SendMobileServiceImpl implements SendService {
	private TSmsServiceManager tSmsServiceManager;
	private SendmsgManager sendmsgManager;
	/**
	 * TODO 简单描述该方法的实现功能（可选）.  
	 * @see com.dwusoft.wbd.send.SendService#sendMessage(java.util.Map)  
	 */
	public boolean sendMessage(Sendmsg message, Map<String, String> params) {
		tSmsServiceManager = (TSmsServiceManager) SpringContextLoader.getBean("tSmsServiceManager");
		//序列号
		String smsSn = "";
		//密码
		String smsPwd = "";
		//webservicedizhi 
		String smsAddress = "";
		//密码加密 md5(sn+password) 32位大写密文
		String md5Pwd = "";
		//特服号
		String msmTf;
		//接收者手机号
		String smsMobile;
		//发送内容
		String smsContent;
		//扩展码
		String smsExt;
		//定时时间
		String smsStime;
		//唯一标识
		String smsRrid;
		//获取当前可用的短信服务商信息
		ParamsVo<TSmsService> vo = new ParamsVo<TSmsService>();
		TSmsService ts = new TSmsService();
		ts.setDelStatus("T");//查询当前可用的，只能有一个可用
		vo.setObj(ts);
		List<TSmsService> list = null;
		try {
			list = tSmsServiceManager.getList(vo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if(Validator.isEmpty(list)){
			return false;
		}
		for (TSmsService s : list) {
			//获取序列号
			smsSn = s.getSmsSn();
			smsPwd = s.getSmsPwd();
			smsAddress = s.getSmsAddress();
			try {
				md5Pwd = MD5Utils.crypt(smsSn+smsPwd).toUpperCase();
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
			//只执行一次
			break;
		}
		smsMobile = message.getToUserMobile();
		smsContent = message.getMsgContent();
		//获取当前准备发送的短信集合
//		ParamsVo<Sendmsg> voS = new ParamsVo<Sendmsg>();
//		Sendmsg msg = new Sendmsg();
//		msg.setDelStatus("F");
//		msg.setMsgStatus("1");//待发送
//		msg.setMsgType("mobile");//类型为短信
//		voS.setObj(msg);
//		List<Sendmsg> listS = sendmsgManager.getList(voS);
//		if(Validator.isEmpty(listS)){
//			return true;
//		}
//		for (Sendmsg m : listS) {
//			smsMobile = m.getToUserMobile();
//			smsContent = m.getMsgContent();
//			//调用发送短信方法
//			sendMsg(smsSn,smsPwd,md5Pwd,smsMobile,smsContent);
//		}
		//调用发送短信方法
		return sendMsg(smsAddress,smsSn,smsPwd,md5Pwd,smsMobile,smsContent);
	}
	/**
	 * @param smsAddress			服務地址
	 * @param smsSn			序列号
	 * @param smsPwd		密码
	 * @param md5Pwd		MD5加密后密码
	 * @param smsMobile		手机号
	 * @param smsContent	内容
	 */
	private boolean sendMsg(String smsAddress,String smsSn,String smsPwd,String md5Pwd,String smsMobile,String smsContent){
		URL url = null;
		try {
			smsContent = URLEncoder.encode(smsContent.replaceAll("<br/>", " "), "GBK");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}//发送内容
		String ext = "";
		String stime = "";
		String rrid = DateUtils.Now.fmt_yyyyMMdd_HHmmssSSS();
		//发送短信
		try {
//			url = new URL("http://sdk.entinfo.cn:8060/webservice.asmx/mt?sn=" + smsSn + "&pwd=" + md5Pwd + "&mobile=" + smsMobile + "&content=" + smsContent
//					+ "&rrid=&ext=&stime=" + stime);
			url = new URL(smsAddress+"mt?sn=" + smsSn + "&pwd=" + md5Pwd + "&mobile=" + smsMobile + "&content=" + smsContent
					+ "&rrid=&ext=&stime=" + stime);
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		}
		BufferedReader in = null;
		System.out.println("开始发送短信start");
		System.out.println("url:"+url);
		String result_mt = "";
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document document = db.parse(url.openStream());
			NodeList bookList = document.getElementsByTagName("string");
			result_mt = bookList.item(0).getTextContent();
			System.out.println(result_mt);
			if (result_mt.startsWith("-") || result_mt.equals(""))//发送短信，如果是以负号开头就是发送失败。
			{
//				System.out.println("发送失败！返回值为：" + result_mt);
			}
		} catch (IOException e) {
			System.out.println("网络异常,发送短信失败！");
			e.printStackTrace();
			result_mt = "-30";
		} catch (Exception e){
			
		}
		System.out.println("结束发送短信返回值1：  " + result_mt);
		if (result_mt.startsWith("-") || result_mt.equals(""))//发送短信，如果是以负号开头就是发送失败。
		{
			return false;
		}
		return true;
	}
	
	public void settSmsServiceManager(TSmsServiceManager tSmsServiceManager) {
		this.tSmsServiceManager = tSmsServiceManager;
	}
	//测试方法
	public static void main(String[] args) throws MalformedURLException,
	UnsupportedEncodingException, ParserConfigurationException {
		URL url = null;
		String sn = "SDK-WSS-010-10097";
		String pwd = "012-10=4-44";
		pwd = "B5A9241D166BA1913AD4241C3584DD3F";
		String mobile = "18511173289";
		mobile = "18500557651";
		String send_content = "您的短信验证码为123456，请立即完成注册，5分钟内有效。【北京木交中心】";//发送内容
		send_content = "您的验证码：234567（手机注册验证码，请完成验证）。切勿告知他人。【北京木交中心】";//发送内容
		send_content = "您的注册验证码为999000。此验证码五分钟内有效。【北京木交中心】";//发送内容
		send_content = "会员org001完成挂牌，项目编号NO10P0000001，挂牌时间2016-11-9 14:23:59【北京木交中心】";
		send_content = "您正在进行北京木交所注册操作，验证码000001，有效期120秒。【北京木交中心】";
//		send_content = "项目编号为111122223333，截止日2016/11/15【北京木交所】";
		send_content = URLEncoder.encode(send_content.replaceAll("<br/>", " "), "GBK");//发送内容
		String ext = "";
		String stime = "";
		String rrid = DateUtils.Now.fmt_yyyyMMdd_HHmmssSSS();
//		String urls = "http://sdk.entinfo.cn:8060/webservice.asmx?sn=" + sn + "&pwd=" + pwd + "&mobile=" + mobile + "&content=" + send_content
//				+ "&rrid=&ext=&stime=" + stime;
//		System.out.println(urls);
		//发送短信
//		url = new URL("http://sdk.entinfo.cn:8060/webservice.asmx/mt?sn=" + sn + "&pwd=" + pwd + "&mobile=" + mobile + "&content=" + send_content
//				+ "&rrid=&ext=&stime=" + stime);
		//查询剩余次数
		pwd = "B5A9241D166BA1913AD4241C3584DD3F";
		url = new URL("http://sdk.entinfo.cn:8060/webservice.asmx/balance?sn=" + sn + "&pwd=" + pwd+"");
		BufferedReader in = null;
		String result_mt = "";
		try {
//			String inputline ;
//			in = new BufferedReader(new InputStreamReader(url.openStream()));
//			while((inputline = in.readLine())!=null){
//				System.out.println("---"+inputline+in.readLine());
//			}
			
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document document = db.parse(url.openStream());
			NodeList bookList = document.getElementsByTagName("string");
			result_mt = bookList.item(0).getTextContent();
//			System.out.println("一共有" + bookList.getLength());
			System.out.println(result_mt);
			
//			result_mt = in.readLine();
			if (result_mt.startsWith("-") || result_mt.equals(""))//发送短信，如果是以负号开头就是发送失败。
			{
				System.out.println("发送失败！返回值为：" + result_mt);
			}
		} catch (IOException e) {
			System.out.println("网络异常,发送短信失败！");
			e.printStackTrace();
			result_mt = "-22";
		} catch (Exception e){
			
		}
		System.out.println("结束发送短信返回值：  " + result_mt);
	}
}
